const ak = import.meta.env.VITE_BAIDU_MAP_AK;
export const loadBaiduMap = () => {
	return new Promise((resolve, reject) => {
		if (window.BMapGL) {
			return resolve(window.BMapGL);
		}

		// 防止重复创建
		if (window.__baiduMapLoading__) return;
		window.__baiduMapLoading__ = true;

		// 清理已有回调
		if (window.__baiduMapInit__) {
			delete window.__baiduMapInit__;
		}

		// 成功回调
		window.__baiduMapInit__ = () => {
			resolve(window.BMapGL);
			window.__baiduMapLoading__ = false;
		};

		const script = document.createElement('script');
		script.type = 'text/javascript';
		script.src = `https://api.map.baidu.com/api?v=1.0&type=webgl&ak=${ak}&callback=__baiduMapInit__`;

		script.onerror = (err) => {
			reject(new Error('百度地图加载失败，请检查网络和AK配置'));
			window.__baiduMapLoading__ = false;
		};

		document.head.appendChild(script);
	});
};
